package com.ericsson.epc.modules.ebmAutoCollector.task;

import com.ericsson.common.pojo.InputStreamChannelExec;
import com.ericsson.common.quartz.task.ManualTask;
import com.ericsson.common.util.*;
import com.ericsson.epc.modules.ebmAutoCollector.entity.EbmAutoDownLoad;
import com.ericsson.epc.modules.ebmAutoCollector.service.EbmService;
import com.jcraft.jsch.JSchException;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import sun.applet.Main;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @description: //凌晨批量执行脚本生成log任务,现在改为每小时的第45分钟执行
 * @author: wangjingshi
 * @create: 2021-02-22 10:56
 */
@Component
public class CreateEbmLogTask implements ManualTask {

    private Logger log = LoggerUtils.Logger(LogFileName.CreateEbmLogJob);

    @Autowired
    private EbmService ebmService;

    @Override
    public void execute() {
        Map<String,Object> paramMap = ebmService.queryParamMap();
        long starttime = new Date().getTime();
        //获取pcap任务的当前小时的上一个小时
        String date = DateUtils.dateRoll(1);//YYYYMMdd_HH
        /*
        //1、获取当前日期前一小时的日期
        String date = DateUtils.beforNumDay(new Date(),
                *//*-1*//*
                -1);*/
        //2、获取前一天日期的所有pcap包所在的文件目录
        List<String> list = new ArrayList<>();
        String ccsccdestPath = (String)((Map)paramMap.get("ccsccdestPath")).get("value");
        String singleEbmScriptPath = (String)((Map)paramMap.get("singleEbmScriptPath")).get("value");
        String[] ips = ((String)((Map)paramMap.get("EbmSingleCollectIps")).get("value")).split(",");
        String username = (String)((Map)paramMap.get("USERNAME")).get("value");
        String password = (String)((Map)paramMap.get("PASSWORD")).get("value");

        File file = new File(ccsccdestPath+date);
        log.info("==== path:" + ccsccdestPath+date);
        List<String> filePathList = FileUtil.func(file,list);
        log.info("==== size:" + filePathList.size());
        //3、遍历pcap文件目录，执行脚本生成单用户ebmlog文件
        for(int i=0;i<filePathList.size();i++){
            try {
                log.info("==== start send cmd:"+filePathList.get(i)+" num:"+i);
                sendSingleEbmCmd(filePathList.get(i),ips,username,password,singleEbmScriptPath);
            }catch (Exception e){
                log.error(" CreateEbmLogTask execute exception",e);
            }finally {
                log.info("==== end send cmd:"+filePathList.get(i)+" num:"+i);
                continue;
            }
        }
        //4、将生成好的log和pcap文件按照ccScc整体打包
        File[] filesInDate = file.listFiles();
        EbmAutoDownLoad ebmAutoDownLoad;
        for (int i = 0; i <filesInDate.length ; i++) {
            FileOutputStream fos1 = null;
            try {
                fos1 = new FileOutputStream(new File(filesInDate[i].getPath()+"("+date+").zip"));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            ZipUtil.toZip(filesInDate[i].getAbsolutePath(), fos1,true);
            FileUtil.deleteDirectory(filesInDate[i].getAbsolutePath());
            String autocollectorpid = filesInDate[i].getName().split("_")[4];
            System.out.println("==============:"+autocollectorpid);
            ebmAutoDownLoad = new EbmAutoDownLoad();
            ebmAutoDownLoad.setAutocollectorpid(autocollectorpid);
            ebmAutoDownLoad.setFilename(filesInDate[i].getName()+"("+date+").zip");
            ebmAutoDownLoad.setDate(DateUtils.getDateTime());
            ebmAutoDownLoad.setPath(ccsccdestPath+date);
            ebmService.insertEbmAutoDownLoad(ebmAutoDownLoad);
        }

        long endtime = new Date().getTime();
        log.info("==== total time :"+(endtime-starttime)/1000/(double)60.00);
    }

    private void sendSingleEbmCmd(String path,String[] ips,String username,String password,String singleEbmScriptPath) {
        String pathArr[] = path.split("\\/");
        //1、取得imsi号码
        String imsiPcap = pathArr[pathArr.length-1];
        String imsi = imsiPcap.substring(13,imsiPcap.length()-5);
        //2、取得开始时间和结束时间
        String interval = pathArr[pathArr.length-2];
        String starttime = interval.split("-")[0];
        String endtime = interval.split("-")[1];
        String date = pathArr[pathArr.length-5].replaceAll("-","").substring(0,8);
        StringBuffer startDatetime = new StringBuffer(starttime);
        StringBuffer endDatetime = new StringBuffer(endtime);
        startDatetime = new StringBuffer(date).append(startDatetime);
        endDatetime = new StringBuffer(date).append(endDatetime);
        //3、把开始时间向前和向后延时1分钟
        String begin = DateUtils.getBeforeNMinDateTime(startDatetime.toString(),5,"yyyyMMddHHmmss");
        String end = DateUtils.getAfterNMinDateTime(endDatetime.toString(),0,"yyyyMMddHHmmss");
        String outputPath = path.replace("pcap","log");
        FileWriter fw = null;
        try {
            fw = new FileWriter(outputPath);
        } catch (IOException e) {
            log.error(" CreateEbmLogTask sendSingleEbmCmd exception",e);
        }
        for(int i=0;i<ips.length;i++){
            //log.info("==== ip:" +ips[i]);
            SSHUtil ssh = new SSHUtil(ips[i],username,password);
            try {
                ssh.connect();
            } catch (JSchException e) {
                log.error(" CreateEbmLogTask sendSingleEbmCmd exception",e);
            }
            String cmd = singleEbmScriptPath + "get_single_user_printout_exact_time.pl -imsi " + imsi + " -ebm_xml_folder "+ singleEbmScriptPath + "MME" +
                    " -start_time " + begin + " -end_time " + end + " -folder_unit day -root_splited_ebm_folder "+ singleEbmScriptPath + "MME/SPLITED";
            log.info("===="+cmd);
            try {
                InputStreamChannelExec Isce = ssh.execCommandReturnStream(cmd);
                BufferedReader br = new BufferedReader(Isce.getIs());
                PrintWriter pw = new PrintWriter(new BufferedWriter(fw));
                int lineCount = 1;
                String ss;
                while((ss=br.readLine()) != null){
                    pw.println(ss);
                    lineCount++;
                }
                pw.close();
            } catch (IOException e) {
                log.error(" CreateEbmLogTask sendSingleEbmCmd exception",e);
            } finally {
                ssh.disconnect();
                continue;
            }
        }
    }
}
